import React, { Component } from 'react'
import "cesium/Source/Widgets/widgets.css"
import buildModuleUrl from "cesium/Source/Core/buildModuleUrl"
import { cesiumBaseUrl } from '../../assets/global';

const Cesium = require('cesium/')
buildModuleUrl.setBaseUrl(cesiumBaseUrl)

export default class Earth3d extends Component {
  constructor(props) {
    super(props);
  }
  componentDidMount() {
    this.viewer = new Cesium.Viewer('home-cesium-container', {
      selectionIndicator: false,
      homeButton: false,
      sceneModePicker: false,//是否显示投影方式控件
      baseLayerPicker: false,//是否显示图层选择控件
      geocoder: false,//是否显示地名查找控件
      navigationHelpButton: false,
      infoBox: false,
      navigationInstructionsInitiallyVisible: false,
      animation: false,
      timeline: false,
      fullscreenButton: false,
      allowTextureFilterAnisotropic: false,
      contextOptions: {
        webgl: {
          alpha: false,
          antialias: true,
          preserveDrawingBuffer: true,
          failIfMajorPerformanceCaveat: false,
          depth: true,
          stencil: false,
          anialias: false
        }
      },
      targetFrameRate: 60,
      resolutionScale: 1.0,
      orderIndependentTranslucency: true,
      automaticallyTrackDataSourceClocks: false,
      dataSources: null,
      clock: null,
      terrainShadows: Cesium.ShadowMode.DISABLED,
      // google卫星影像（需要翻墙）
      // imageryProvider: new Cesium.UrlTemplateImageryProvider({
      //   url: 'http://www.google.cn/maps/vt?lyrs=s@800&x={x}&y={y}&z={z}',
      //   tilingScheme: new Cesium.WebMercatorTilingScheme(),
      //   minimumLevel: 1,
      //   maximumLevel: 20
      // }),
      // 天地图影像
      imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
        url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=050f735ae3f59ad37aacb56801a0bb10",
        layer: "tdtBasicLayer",
        style: "default",
        format: "image/jpeg",
        tileMatrixSetID: "GoogleMapsCompatible",
        show: false
      }),
      // 世界地形
      // terrainProvider: new Cesium.createWorldTerrain({
      //   requestWaterMask: true,
      //   requestVertexNormals: true
      // }),
      // terrainExaggeration: 1.5
    });

    // 天地图注记图层
    this.viewer.imageryLayers.addImageryProvider(new Cesium.WebMapTileServiceImageryProvider({
      url: "http://t1.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=050f735ae3f59ad37aacb56801a0bb10",
      layer: "tdtAnnoLayer",
      style: "default",
      format: "image/jpeg",
      tileMatrixSetID: "GoogleMapsCompatible"
    }));

    // 设置home在中国
    // const portCenter = [119.39, 34.7];
    const ChinaRectangle = Cesium.Rectangle.fromDegrees(73.0, 3.0, 135.0, 53.0);
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = ChinaRectangle;
    this.viewer.camera.flyHome(5);


    // 镜头拉近
    const ellipsoid = this.viewer.scene.globe.ellipsoid;
    const cameraHeight = ellipsoid.cartesianToCartographic(this.viewer.camera.position).height;
    this.viewer.camera.zoomIn(cameraHeight / 3);


    // 添加球的动画
    setTimeout(() => {
      const flyObjList = this.flyInit();
      let animationSpend = this.flyPath(flyObjList) + 2000;
      setInterval(() => {
        this.flyPath(flyObjList);
      }, animationSpend);
    }, 5000);

  }

  flyInit = () => {
    // 飞行高度
    const tall_height = 10000;
    const height = 3000;
    // 飞行路径
    const path = [[119.5814625150, 34.5996203047, tall_height], //徐总览点
    [119.6089906777, 34.5746314286, height],  //起点徐1
    [119.5563945193, 34.6065072025, height],  //徐2
    [119.4947301507, 34.7093118340, tall_height], //连总览点
    [119.4996741012, 34.7248014737, height],   //连1
    [119.4494220180, 34.7511943703, height],   //连2
    [119.4053595078, 34.7543465070, height],   //连3
    [119.2946927623, 35.0311515732, height]    //终点赣1
    ];
    const portNameArr = ["xuweiPort", "xuweiPort", "lianyunPort", "lianyunPort", "lianyunPort", "lianyunPort", "ganyuPort", ""];


    const timeSpend = 60;  //飞行总时长

    const flyObjList = [{
      origin: path[0], //目标点
      dest: path[0],
      heading: Cesium.Math.toRadians(0),
      len: 0,
      spend: 0,
      realSpend: 0,
      portName: portNameArr[0]
    }];

    const pitchDegree = Cesium.Math.toRadians(60);  //？？？

    // 计算飞行距离（只适用于小范围，忽略经纬度的距离差异）
    let pathLength = 0;
    for (let i = 0, l = path.length, j = 0; i < l - 1; i++, j++) {
      const pre = path[i];
      const post = path[i + 1];
      const dx = pre[0] - post[0];
      const dy = pre[1] - post[1];

      const singleLen = Math.sqrt(dx * dx + dy * dy);
      pathLength += singleLen;


      flyObjList.push({
        origin: post,
        dest: path[i + 1],
        heading: Math.atan(dx / dy),
        len: singleLen,
        spend: 0,
        realSpend: 0,
        portName: portNameArr[i]
      });

    }

    flyObjList.forEach((item) => {
      //每一段的飞行时间，共计飞行时间为timespend
      item.spend = item.len / pathLength * timeSpend;
      // 因为有相机角度的原因，飞行时间在小于预定时间时即可到达位置，所以要设置实际飞行时间
      item.realSpend = item.spend * Math.sin(pitchDegree);
      //控制速度
      if (item.len < 0.1 && item.origin[2] !== tall_height) {
        item.spend *= 4;
        item.realSpend *= 4;
      }
      else {
        item.spend /= 2;
        item.realSpend /= 2;
      }

    })

    return flyObjList;
  }

  flyPath = (flyObjList) => {
    const pitch = Cesium.Math.toRadians(-80);    // 相机看的角度，负值代表从上往下看

    // 飞行到第一个点
    const firstPoint = flyObjList[0].dest;
    this.viewer.camera.flyTo({
      destination: Cesium.Cartesian3.fromDegrees(firstPoint[0], firstPoint[1], firstPoint[2]),
      orientation: {
        heading: flyObjList[0].heading,
        pitch: pitch,
      },
      duration: 3
    });

    this.props.destinationPort && this.props.destinationPort(flyObjList[0].portName);
    // 飞到第一个点之后停留5s
    let timeLine = 3000 + 5000;
    for (let i = 1, l = flyObjList.length; i < l; i++) {

      const lastDest = flyObjList[i - 1].origin;
      const lastDestPosition = Cesium.Cartesian3.fromDegrees(lastDest[0], lastDest[1], lastDest[2]);
      const towards = flyObjList[i].heading;

      const nextPoint = flyObjList[i].origin;
      const nextPosition = Cesium.Cartesian3.fromDegrees(nextPoint[0], nextPoint[1], nextPoint[2]);

      const flyTimeSpend = flyObjList[i].spend;
      const flyTimeRealSpend = flyObjList[i].realSpend;


      /*   const nextDest = flyObjList[i].dest;
        const nextDestPosition = Cesium.Cartesian3.fromDegrees(nextDest[0], nextDest[1], nextDest[2]);  */
      this.asyncFlyTo({
        // 调整镜头方向
        destination: lastDestPosition,
        orientation: {
          heading: towards,
          pitch: Cesium.Math.toRadians(-80),//？？
        },
        duration: 2,
        easingFunction: Cesium.EasingFunction.LINEAR_NONE  //匀速飞行
      }, 2000, timeLine)
        .then(() => {
          this.asyncFlyTo({
            // 飞向下一个点
            destination: nextPosition,
            orientation: {
              heading: towards,
              pitch: Cesium.Math.toRadians(-60),
            },
            duration: flyTimeSpend,
            easingFunction: Cesium.EasingFunction.LINEAR_NONE
          }); this.props.destinationPort && this.props.destinationPort(flyObjList[i].portName)
        }, flyTimeSpend * 1000, 500).then(() => { this.props.destinationPort && this.props.destinationPort(flyObjList[i].portName) });
      /* .then(() => this.asyncFlyTo({
        // 摆正镜头
        destination: nextDestPosition,
        orientation: {
          heading: 0,
          pitch: pitch,
        },
        duration: 5,
        easingFunction: Cesium.EasingFunction.LINEAR_NONE
      }, 5000, 500));  */

      // 2次飞行的时间间隔：3s调整镜头+飞行时间+5s摆正镜头+5s停留时间+1s等待时间
      timeLine += (2000 + flyTimeRealSpend * 1000 + 5000 + 5000);
    }

    // 所有飞行完成后，停留5s，镜头拉回全局
    timeLine += 5000;
    setTimeout(() => {
      this.viewer.camera.flyHome(5);

      this.props.destinationPort && this.props.destinationPort("");
    }, timeLine);
    timeLine += 5000;


    return timeLine;
  }

  /*
   * return: Promise对象
   * option：flyTo的参数
   * duration: flyTo的持续时间（ms）
   * wait: 等待时间，等待n毫秒后执行flyTo
   */
  asyncFlyTo = (options, duration, wait = 0) => {
    return new Promise(resolve => {
      setTimeout(() => {
        this.viewer.camera.flyTo(options);
        setTimeout(() => resolve(), duration);
      }, wait);
    });
  }

  // cesiumFlyAnimation = (center) => {
  //   // 飞行到港区区域
  //   const point = [119.59, 34.6, 20000]
  //   const pitch = Cesium.Math.toRadians(-80);    // 相机看的角度，负值代表从上往下看
  //   this.viewer.camera.flyTo({
  //     destination: Cesium.Cartesian3.fromDegrees(point[0], point[1], point[2]),
  //     orientation: {
  //       heading: Cesium.Math.toRadians(0),
  //       pitch: pitch,
  //       // roll: Cesium.Math.toRadians(0)
  //     },
  //     duration: 3
  //   });

  //   this.viewer.scene.camera.moveBackward(point[2]);



  //   setTimeout(() => {
  //     const position = Cesium.Cartesian3.fromDegrees(point[0], point[1], point[2]);  // 相机看的位置
  //     this.wheelAroundPoint(position, pitch);
  //   }, 5000);


  //   // 盘旋后返回地球视角
  //   // setTimeout(() => {
  //   //   this.viewer.camera.flyHome(5);
  //   // }, 5000);
  // }

  // // 进行盘旋  
  // wheelAroundPoint = (position, pitch) => {
  //   const distance = 0;  // 相机距离点的距离    
  //   const omega = -360 / 15;  // 转动的角速度（度/s），360度除以旋转一周的时间

  //   this.viewer.clock.startTime = Cesium.JulianDate.fromDate(new Date()).clone();  //开始时间
  //   this.viewer.clock.currentTime = Cesium.JulianDate.fromDate(new Date()).clone();  //当前时间
  //   this.viewer.clock.clockRange = Cesium.ClockRange.CLAMPED; // 行为方式
  //   this.viewer.clock.clockStep = Cesium.ClockStep.SYSTEM_CLOCK; // 时钟设置为当前系统时间; 忽略所有其他设置。

  //   // const initHeading = Cesium.Math.toRadians(0);
  //   const initHeading = this.viewer.camera.heading;

  //   const wheel = () => {
  //     // 已经经过的时间
  //     const passedTime = Cesium.JulianDate.secondsDifference(this.viewer.clock.currentTime, this.viewer.clock.startTime);
  //     // 根据已经经过的时间换个角速度计算当前的heading
  //     const heading = Cesium.Math.toRadians(passedTime * omega) + initHeading;
  //     // 改变相机view
  //     this.viewer.scene.camera.setView({
  //       destination: position,
  //       orientation: {
  //         heading: heading,
  //         pitch: pitch,
  //       }
  //     });

  //     this.viewer.scene.camera.moveBackward(distance);
  //     if (Cesium.JulianDate.compare(this.viewer.clock.currentTime, this.viewer.clock.stopTime) >= 0) {
  //       this.viewer.clock.onTick.removeEventListener(wheel);
  //     }
  //   }
  //   this.viewer.clock.onTick.addEventListener(wheel);
  // }

  render() {
    return (
      <div id='home-cesium-container' style={{ height: '100%' }} />
    );
  }
}
